package com.cy.config;

import com.cy.io.Resources;
import com.cy.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlConfiguration {

    /**
     * 将输入流转换为Configuration
     * @param in
     * @return
     */
    public Configuration parse(InputStream in) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();

        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();

        for (Element element : list) {
            properties.setProperty(element.attributeValue("name"), element.attributeValue("value"));
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        Configuration configuration = new Configuration();
        configuration.setDataSource(comboPooledDataSource);

        List<Element> mapperList = rootElement.selectNodes("//mapper");

        for (Element element : mapperList) {

            String resource = element.attributeValue("resource");
            InputStream mapperResourceIn = Resources.getResourcesAsInputStream(resource);

            //解析mapper.xml
            XmlMappedStatement xmlMappedStatement = new XmlMappedStatement();
            xmlMappedStatement.parse(configuration, mapperResourceIn);
        }

        return configuration;
    }

}
